package com.ruoyi.controller;

import com.ruoyi.service.FileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传控制器
 * 提供文件和图片的上传接口
 */
@RestController
@RequestMapping("/api/upload")
public class FileUploadController {

    /**
     * 自动注入文件上传服务
     */
    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 上传文件接口
     * 处理文件上传请求
     *
     * @param file 要上传的文件
     * @return 返回包含文件URL的响应实体
     */
    @PostMapping("/file")
    public ResponseEntity<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 调用服务上传文件并获取文件URL
            String fileUrl = fileUploadService.uploadFile(file);
            // 构建成功响应
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("url", fileUrl);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 构建失败响应
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 上传图片接口
     * 处理图片上传请求
     *
     * @param file 要上传的图片文件
     * @return 返回包含图片URL的响应实体
     */
    @PostMapping("/image")
    public ResponseEntity<Map<String, Object>> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            // 调用服务上传图片并获取图片URL
            String imageUrl = fileUploadService.uploadImage(file);
            // 构建成功响应
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("url", imageUrl);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 构建失败响应
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}
